import './queryPanel.css'
import { Select, Button } from 'antd'
import { arrayHelper } from '@/utils/common'
import { useState, useRef, useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useParams, useSearchParams } from 'next/navigation'
import { apiClient } from '@/lib/apiClient'

function QueryItem ({ 
    type,
    value,
    label, 
    options,
    queryHandle,
}) {

    const [selectWidth, setSelectWidth] = useState(() => (160))
    const selectRef = useRef()

    useEffect(() => {
        if (selectRef.current) {
            const width = selectRef.current.offsetWidth
            if (width > 292) {
                setSelectWidth(() => (220))
            }

            if (width < 292) {
                setSelectWidth(() => (width - 80))
            }
        }
    }, [])

    const handleChangeSelect = (value) => {
        if (typeof queryHandle === 'function') {
            queryHandle(value)
        }
    }

    const selectType = (((type) => {
        if (type === 'single') {
            return ''
        }

        if (type === 'multiple') {
            return 'multiple'
        }

        return ''
    })(type))

    return (
        <div className='text-sm flex items-center' ref={selectRef}>
            <label className="block after:content-[':'] mr-3">
                {label}
            </label>
            <Select 
                style={{ width: `${selectWidth}px` }}
                placeholder="请选择"
                mode={selectType}
                value={value}
                allowClear
                options={arrayHelper(options)}
                onChange={handleChangeSelect}
                maxTagCount='responsive'
            />
        </div>
    )
}

export default function QueryPanel ({ queryHandle }) {
    const params = useParams()
    const searchParams = useSearchParams()

    const { error, data, status } = useQuery({
        queryKey: ['query_options', params?.id],
        queryFn: async () => {
            const data = await apiClient.post(
                `graphAnalysis/getSelectCondition`,
                {
                    json: {
                        idCard: params?.id,
                    }
                },
            ).json()

            return data
        },
        select: (result) => {
            let associationMethodOptions = []
            let litigantOptions = []
            let resourceOptions = []
            let codeOptions = []
            let typeOptions = []
            let idOptions = []
            let occurrenceTimeOptions = []

            if (result.code === 200) {
                if (result.data?.associationTypes) {
                    associationMethodOptions = arrayHelper(result.data.associationTypes).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.disputePersonNames) {
                    litigantOptions = arrayHelper(result.data.disputePersonNames).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.disputeSources) {
                    resourceOptions = arrayHelper(result.data.disputeSources).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.disputeIds) {
                    codeOptions = arrayHelper(result.data.disputeIds).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.disputeTypes) {
                    typeOptions = arrayHelper(result.data.disputeTypes).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.disputePersonIds) {
                    idOptions = arrayHelper(result.data.disputePersonIds).map((item) => { return { label: item?.name, value: item?.value } })
                }

                if (result.data?.occurrenceTime) {
                    occurrenceTimeOptions = arrayHelper(result.data.occurrenceTime).map((item) => { return { label: item?.name, value: item?.value } })
                }
            }

            return {
                associationMethodOptions,
                litigantOptions,
                resourceOptions,
                codeOptions,
                typeOptions,
                idOptions,
                occurrenceTimeOptions,
            }
        }
    })

    let associationMethodOptions = []
    let litigantOptions = []
    let resourceOptions = []
    let codeOptions = []
    let typeOptions = []
    let idOptions = []
    let occurrenceTimeOptions = [] 

    if (status === 'success') {
        associationMethodOptions = data.associationMethodOptions
        litigantOptions = data.litigantOptions
        resourceOptions = data.resourceOptions
        codeOptions = data.codeOptions
        typeOptions = data.typeOptions
        idOptions = data.idOptions
        occurrenceTimeOptions = data.occurrenceTimeOptions
    }

    const [selectedAssociationMethod, setSelectedAssociationMethod] = useState(() => (undefined))
    const [selectedLitigant, setSelectedLitigant] = useState(() => (undefined))
    const [selectedResource, setSelectedResource] = useState(() => (undefined))
    const [selectedCode, setSelectedCode] = useState(() => (undefined))
    const [selectedType, setSelectedType] = useState(() => (undefined))
    const [selectedId, setSelectedId] = useState(() => (undefined))
    const [selectedOccurrenceTime, setSelectedOccurrenceTime] = useState(() => (undefined))

    const queryHelper = () => {
        if (typeof queryHandle === 'function') {
            queryHandle({
                selectedAssociationMethod: selectedAssociationMethod ?? [],
                selectedLitigant: selectedLitigant ?? [],
                selectedResource: selectedResource ?? '',
                selectedCode: selectedCode ?? '',
                selectedType: selectedType ?? '',
                selectedId: selectedId ?? '',
                selectedOccurrenceTime: selectedOccurrenceTime ?? '',
            })
        }
    }

    useEffect(() => {
        queryHelper()
    }, [])

    useEffect(() => {
        if (Array.isArray(litigantOptions) && litigantOptions.length > 0) {
            if (litigantOptions.find((item) => { return item?.value === searchParams.get('litigant') })) {
                setSelectedLitigant(() => ([searchParams.get('litigant')]))

                if (typeof queryHandle === 'function') {
                    queryHandle({
                        selectedAssociationMethod: selectedAssociationMethod ?? [],
                        selectedLitigant: [searchParams.get('litigant')],
                        selectedResource: selectedResource ?? '',
                        selectedCode: selectedCode ?? '',
                        selectedType: selectedType ?? '',
                        selectedId: selectedId ?? '',
                        selectedOccurrenceTime: selectedOccurrenceTime ?? '',
                    })
                }
            }
        }
    }, [litigantOptions])

    const resetQuery = () => {
        setSelectedAssociationMethod(() => (undefined))
        setSelectedLitigant(() => (undefined))
        setSelectedResource(() => (undefined))
        setSelectedCode(() => (undefined))
        setSelectedType(() => (undefined))
        setSelectedId(() => (undefined))
        setSelectedOccurrenceTime(() => (undefined))

        if (typeof queryHandle === 'function') {
            queryHandle({
                selectedAssociationMethod: [],
                selectedLitigant: [],
                selectedResource: '',
                selectedCode: '',
                selectedType: '',
                selectedId: '',
                selectedOccurrenceTime: '',
            })
        }
    }



    useEffect(() => {

        const keydownHandle = (e) => {
            if (e.key === 'Enter') {
                queryHelper()
            }
        }

        document.addEventListener('keydown', keydownHandle)

        return () => {
            document.removeEventListener('keydown', keydownHandle)
        }
    }, [])

    return (
        <div className='query-panel-container'>
            <div className='query-container'>
                <div className='query-association-method'>
                    <QueryItem 
                        label="关联方式"
                        value={selectedAssociationMethod}
                        options={associationMethodOptions} 
                        type="multiple"
                        queryHandle={(value) => (setSelectedAssociationMethod(() => (value)))}
                    />
                </div>
                <div className='query-litigant'>
                    <QueryItem 
                        label="纠纷对象"
                        value={selectedLitigant}
                        options={litigantOptions}
                        type="multiple"
                        queryHandle={(value) => (setSelectedLitigant(() => (value)))}
                    />
                </div>
                <div className='query-resource'>
                    <QueryItem 
                        label="纠纷来源"
                        value={selectedResource}
                        options={resourceOptions}
                        queryHandle={(value) => (setSelectedResource(() => (value)))}
                    />
                </div>
                <div className='query-code'>
                    <QueryItem 
                        label="纠纷编号"
                        value={selectedCode}
                        options={codeOptions}
                        queryHandle={(value) => (setSelectedCode(() => (value)))}
                    />
                </div>
                <div className='query-type'>
                    <QueryItem 
                        label="纠纷类型" 
                        value={selectedType}
                        options={typeOptions}
                        queryHandle={(value) => (setSelectedType(() => (value)))}
                    />
                </div>
                <div className='query-id'>
                    <QueryItem 
                        label="身份证号" 
                        value={selectedId}
                        options={idOptions}
                        queryHandle={(value) => (setSelectedId(() => (value)))}
                    />
                </div>
                <div className='query-occurrence-time'>
                    <QueryItem 
                        label="发生时间" 
                        value={selectedOccurrenceTime}
                        options={occurrenceTimeOptions}
                        queryHandle={(value) => (setSelectedOccurrenceTime(() => (value)))}
                    />
                </div>
            </div>
            <div className='query-button-container flex flex-col justify-end'>
                <div className='flex'>
                    <Button type='primary' onClick={queryHelper}>
                        查询
                    </Button>
                    <Button style={{ marginLeft: '16px' }} onClick={resetQuery}>
                        重置
                    </Button>
                </div>
            </div>
        </div>
    )
}